package com.qpx.shoppingcarservice.service;


import com.qpx.shoppingcarservice.entity.ShoppingCarEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


@Service
public class ShoppingCarService {


    @Autowired
    MongoTemplate mongoTemplate;
    public void addCar(ShoppingCarEntity shoppingCarEntity){
        Query query = new Query();
        query.addCriteria(Criteria.where("itemId").is(shoppingCarEntity.getItemId()));
        query.addCriteria(Criteria.where("uid").is(shoppingCarEntity.getUid()));
        ShoppingCarEntity one = mongoTemplate.findOne(query, ShoppingCarEntity.class);
        //说明购物车已经存在
        if (one!=null){
            //修改的过程  累加的过程
            Update update = Update.update("sum",one.getSum()+shoppingCarEntity.getSum());
            mongoTemplate.updateFirst(query,update,ShoppingCarEntity.class);
            return;
        }

        mongoTemplate.save(shoppingCarEntity);

    }

    public void updateCar(ShoppingCarEntity shoppingCarEntity) {
        Query query = new Query();
        query.addCriteria(Criteria.where("itemId").is(shoppingCarEntity.getItemId()));
        query.addCriteria(Criteria.where("uid").is(shoppingCarEntity.getUid()));
        Update update = Update.update("sum",shoppingCarEntity.getSum());
        mongoTemplate.updateFirst(query,update,ShoppingCarEntity.class);
    }
}
